<template>
  <!-- 轮播图弹窗 -->
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :close-on-press-escape="false" width="600px">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="80px">
      <el-form-item prop="realName" label="姓名">
        <el-input v-model.trim="dataForm.realName" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item prop="userTag" label="标签">
        <el-input v-model.trim="dataForm.userTag" placeholder="标签"></el-input>
      </el-form-item>
      <el-form-item prop="gender" label="性别">
        <el-radio-group v-model="dataForm.gender">
          <el-radio :value="0" size="large">男</el-radio>
          <el-radio :value="1" size="large">女</el-radio>
          <el-radio :value="2" size="large">保密</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="age" label="年龄">
        <el-input v-model.trim="dataForm.age" maxlength="3" placeholder="年龄" @input="(e)=>handleInput(e,1)"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="手机号">
        <el-input v-model.trim="dataForm.mobile" maxlength="11" placeholder="手机号" @input="(e)=>handleInput(e,2)"></el-input>
      </el-form-item>
      <el-form-item prop="province" label="省份">
        <el-select v-model="dataForm.province" placeholder="省份" clearable filterable>
          <el-option v-for="(item,index) in provinceList" :key="index" :label="item.value" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="headUrl" label="头像">
        <div class="updateImg-box">
          <updateImg ref="uploadRef" :urlList="dataForm.urlList" @updatImgList="updatImgList"></updateImg>
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, nextTick } from "vue";
import baseService from "@/service/baseService";
import { IObject } from "@/types/interface";
import { ElMessage } from "element-plus";
import updateImg from "@/components/updateImg.vue";
import province from "@/utils/province.json";
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const uploadRef = ref();
const provinceList = ref(province);

const dataForm = reactive<IObject>({
  id: "",
  realName: "",
  userTag: "",
  gender: 0,
  age: "",
  mobile: "",
  province: "",
  headUrl: "",
  urlList: []
});

// 校验手机号输入
const validatorPhone = (rule: any, value: any, callback: any) => {
  let ver = /^1[0-9]{10}$/; //以1开头
  if (value === "") {
    callback(new Error("必填项不能为空"));
  } else if (!ver.test(value)) {
    callback(new Error("请填写正确的手机号"));
  } else {
    callback();
  }
};

const rules = ref({
  realName: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  userTag: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  // age: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  mobile: [{ required: true, validator: validatorPhone, trigger: "blur" }],
  gender: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  // province: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  headUrl: [{ required: true, message: "必填项不能为空", trigger: "change" }]
});

const init = async (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataForm.urlList = [];
    dataFormRef.value.resetFields();
  }

  if (id) {
    await getInfo(id);
  }

  await nextTick(() => {
    uploadRef.value.init();
  });
};

// 获取信息
const getInfo = async (id: number) => {
  await baseService.get(`/lingyao/student/${id}`).then((res) => {
    res.data.urlList = res.data.headUrl
      ? [
          {
            name: "头像",
            url: res.data.headUrl
          }
        ]
      : [];
    Object.assign(dataForm, res.data);
  });
};

// 处理年龄和手机号只能输入正整数
const handleInput = (val: any, type: number) => {
  // 使用正则表达式过滤非数字字符
  let inputValue;
  inputValue = val.replace(/\D/g, "");

  if (type == 1) {
    dataForm.age = inputValue;
  } else {
    dataForm.mobile = inputValue;
  }
};

// 上传图片成功
const updatImgList = (list: any[]) => {
  dataForm.headUrl = list.length > 0 ? list[0].url : "";
  dataForm.urlList = list;
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/lingyao/student", dataForm).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
